package com.example.itcompanyinterview.tools;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.itcompanyinterview.object.AppCommonInfo;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.widget.ProgressBar;
import android.widget.Toast;

public class ClientUpdateManager {
	
	private static final int DOWNLOADING = 1;
	private static final int DOWNLOAD_FINISH = 2;
	private static final int NEW_VERSION_FOUND = 999;
	private String savePath = "apk";
	private String saveFile = "ITCompanyInterview.apk";
	private int processStatus;
	private ProgressDialog progressDialog;
	private AppCommonInfo appCommonInfo;
	private Context context;
	
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch(msg.what) {
			case NEW_VERSION_FOUND:
				ShowUpdateDialog();
				break;
			case DOWNLOADING:
				progressDialog.setProgress(processStatus);
				break;
			case DOWNLOAD_FINISH:
				installApk();
				break;
			}
		}
	};
	
	public ClientUpdateManager(Context context) {
		this.context = context;
	}
	
	public void installApk() {
		File apkFile = new File(CommonFileTools.getLocalPath(savePath) + saveFile);
		if(!apkFile.exists()) {
			return;
		}
		
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.parse("file://" + apkFile.toString()),
				"application/vnd.android.package-archive");
		this.context.startActivity(intent);
	}

	
	public void ShowUpdateDialog() {
		AlertDialog dialog = new AlertDialog.Builder(this.context).create();
		dialog.setTitle("系统更新提示");
		dialog.setMessage("发现新版本，请下载更新！");
		dialog.setButton(DialogInterface.BUTTON_POSITIVE, "确认", 
    			new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						progressDialog = new ProgressDialog(context);
						progressDialog.setTitle("正在下载");
						progressDialog.setMessage("请稍候...");
						progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
						downloadFile();
					}
				}
    	);
		dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", 
    			new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						System.exit(0);
					}
				}
    	);
 
		dialog.show();
	}
	
	private void downloadFile() {
		progressDialog.show();
		final String apkUrl = appCommonInfo.getLatestVersionUrl();
		new Thread() {
			public void run() {
				try{
					if(Environment.getExternalStorageState().
							equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
						String apkFilePath = CommonFileTools.getLocalPath(savePath);
						URL url = new URL(apkUrl);
						HttpURLConnection conn = (HttpURLConnection)url.openConnection();
						conn.connect();
						int length = conn.getContentLength();
						InputStream in = conn.getInputStream();
						File apkFile = CommonFileTools.openFile(apkFilePath, saveFile);
						FileOutputStream fos = new FileOutputStream(apkFile);
						int count = 0; 
						byte buf[] = new byte[1024];
						int readNum = -1;
						while((readNum = in.read(buf)) > 0) {
							count += readNum;
							processStatus = (int)(((float) count/length) * 100);
							handler.sendEmptyMessage(DOWNLOADING);
							fos.write(buf, 0, readNum);
						}
						fos.close();
						in.close();
						downloadFinish();
					}
				}catch(Exception e) {
					Toast.makeText(context, "下载文件失败", Toast.LENGTH_LONG).show();
				}
			}
		}.start();
	}
	
	private void downloadFinish() {
		progressDialog.dismiss();
		handler.sendEmptyMessage(DOWNLOAD_FINISH);
	}
	
	public void checkUpdate() {
		new Thread(new Runnable(){
			public void run() {
				String appJsonString = CommonUrlRequest.getControllerAndAction("Common", "GetAppInfo");
				if(appJsonString == null) {
					return;
				}
				
				JSONObject appObj = CommonJsonParser.parseJsonObject(appJsonString);
				if(appObj == null ) {
					return;
				}
				
				try {
					appCommonInfo = new AppCommonInfo(appObj.getString("value"));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				if(isNeedUpdate()) {
					handler.sendEmptyMessage(NEW_VERSION_FOUND);
				}
			}
		}).start();
	}

	
	public boolean isNeedUpdate() {
		int currVersion = this.getCurrVersion();
		int latestVersion = this.appCommonInfo.getLatestVersion();
		if (currVersion < latestVersion) {
			return true;
		} else {
			return false;
		}
	}
	
	private int getCurrVersion() {
		int versionCode = 0;
		try {
			versionCode = context.getPackageManager().
					getPackageInfo(context.getPackageName(), 0).versionCode;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return versionCode;
	}
}
